package com.elinkway.infinitemovies.http.parser;

import android.text.TextUtils;

import com.elinkway.infinitemovies.bean.OutSiteStreamEntity;
import com.elinkway.infinitemovies.bean.OutSiteStreamInfo;
import com.elinkway.infinitemovies.bean.StreamDownNewPriority;
import com.elinkway.infinitemovies.bean.StreamPlayPriority;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 新流解析
 * Created by wangyemin on 2015/12/7.
 */
public class OutSiteStreamInfoParser extends LVideoMobileParser<OutSiteStreamInfo> {

    private static String STATUS = "status";
    private static String CODE = "200";
    private static String NEW_VERSION = "newversion";
    private static String ALLOW_FORMATS = "allowFormats";
    private static String REQUEST_FORMAT = "requestFormat";
    private static String OS_TYPE = "osType";
    private static String EID = "eid";
    private static String CLIENTPARSETYPE = "clientParseType";
    private static String IS_DOWNLOAD = "isDownload";
    private static String STREAM_LIST = "stream_list";
    private static String API_LIST = "api_list";
    private static String HEADER = "header";
    private static String USER_AGENT = "User-Agent";
    private static String RULE = "rule";
    private static String TE = "te";
    private static String TS = "ts";
    private static String TOTAL_DURATION = "totalDuration";
    private static String DURATION_LIST = "durationList";

    private static String ANDROID = "ANDROID";
    private static String IOS = "IOS";
    private static String NORMAL = "NORMAL";
    private static String HIGH = "HIGH";
    private static String SUPER = "SUPER";
    private static String SUPER2 = "SUPER2";
    private static String REAL = "REAL";

    private int type; //解析类型 0：播放 1：下载

    public OutSiteStreamInfoParser(int type) {
        this.type = type;
    }

    @Override
    public OutSiteStreamInfo parse(JSONObject data) throws Exception {
        OutSiteStreamInfo streamInfo = null;
        if (data != null && data.has(STATUS) && CODE.equalsIgnoreCase(data.getString(STATUS)) && data.has(NEW_VERSION)) {
            streamInfo = new OutSiteStreamInfo();
            JSONArray newversion = data.optJSONArray(NEW_VERSION);
            if (newversion != null && newversion.length() > 0) {
                int newversionSize = newversion.length();
                LogUtils.e(Utils.TAG, "OutSiteStreamInfoParser newversionSize is " + newversionSize);
                List<OutSiteStreamEntity> streamEntityQueue = new LinkedList<OutSiteStreamEntity>();
                List<String> formatsList = new ArrayList<>();
                for (int i = 0; i < newversionSize; i++) {
                    OutSiteStreamEntity streamEntity = new OutSiteStreamEntity();
                    JSONObject streamObject = (JSONObject) newversion.get(i);
                    if (streamObject != null) {
                        String requestFormat = null;
                        String osType = null;
                        if (streamObject.has("totalSize")) {
                            String totleSize = streamObject.optString("totalSize");
                            BigDecimal bigDecimal = new BigDecimal(totleSize);
                            streamEntity.setTotalSize(bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
                        }

                        JSONArray fSizeList = null;
                        if (streamObject.has("fSizeList")) {
                            fSizeList = streamObject.optJSONArray("fSizeList");
                        }

                        if (fSizeList != null && fSizeList.length() > 0) {
                            for (int j = 0; j < fSizeList.length(); j++) {
                                String currentSize = String.valueOf(fSizeList.get(j));
                                BigDecimal bigDecimal = new BigDecimal(currentSize);
                                streamEntity.getfSizeList().add(bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
                            }
                        }

                        // allowFormats
                        if (streamObject.has(ALLOW_FORMATS)) {
                            JSONArray allowFormatsArr = streamObject.getJSONArray(ALLOW_FORMATS);
                            streamEntity.setAllowFormats(setListValue(allowFormatsArr));
                            if(formatsList.size() != 0){
                                formatsList.removeAll(streamEntity.getAllowFormats());
                            }
                            formatsList.addAll(streamEntity.getAllowFormats());
                        }

                        if (streamObject.has(REQUEST_FORMAT)) {
                            requestFormat = streamObject.getString(REQUEST_FORMAT);
                            streamEntity.setRequestFormat(requestFormat);
                        }
                        if (streamObject.has(OS_TYPE)) {
                            osType = streamObject.getString(OS_TYPE);
                            streamEntity.setOsType(osType);
                        }
                        // Priority
                        streamEntity.setPriority(getStreamPriority(osType, requestFormat, type));

                        if (streamObject.has(EID))
                            streamEntity.setEid(streamObject.getString(EID));

                        if (streamObject.has(CLIENTPARSETYPE)) {
                            streamEntity.setClientParseType(streamObject.getString(CLIENTPARSETYPE));
                        }

                        if (streamObject.has(TOTAL_DURATION)) {
                            streamEntity.setTotalDuration(streamObject.optString(TOTAL_DURATION));
                        }
                        if (streamObject.has(DURATION_LIST)) {
                            JSONArray durationList = streamObject.getJSONArray(DURATION_LIST);
                            streamEntity.setDurationList(setListValue(durationList));
                        }
                        if (streamObject.has(IS_DOWNLOAD))
                            streamEntity.setIsDownload(streamObject.getString(IS_DOWNLOAD));

                        // stream_list
                        if (streamObject.has(STREAM_LIST)) {
                            JSONArray stream_listArr = streamObject.getJSONArray(STREAM_LIST);
                            streamEntity.setStream_list(setListValue(stream_listArr));
                        }

                        // api_list
                        if (streamObject.has(API_LIST)) {
                            JSONArray api_listArr = streamObject.getJSONArray(API_LIST);
                            streamEntity.setApi_list(setListValue(api_listArr));
                        }

                        // User-Agent
                        if (streamObject.has(HEADER)) {
                            JSONObject headerObject = streamObject.getJSONObject(HEADER);
                            if (headerObject != null && headerObject.has(USER_AGENT))
                                streamEntity.setUser_agent(headerObject.getString(USER_AGENT));
                        }

                        // rule
                        Map<String, String> rule = new HashMap<String, String>();
                        if (streamObject.has(RULE)) {
                            JSONObject ruleObject = new JSONObject(streamObject.optString(RULE));
                            if (ruleObject != null) {
                                streamEntity.setIsHasRule(true);
                                if (ruleObject.has(TE))
                                    rule.put(TE, ruleObject.getString(TE));
                                if (ruleObject.has(TS))
                                    rule.put(TS, ruleObject.getString(TS));
                                streamEntity.setRule(rule);
                            } else
                                streamEntity.setIsHasRule(false);
                        } else
                            streamEntity.setIsHasRule(false);
                    }
                    streamEntityQueue.add(streamEntity);
                }
                LogUtils.e(Utils.TAG, "OutSiteStreamInfoParser streamEntityQueue size is " + streamEntityQueue.size());
                LogUtils.e(Utils.TAG, "OutSiteStreamInfoParser before sort streamEntityQueue is " + streamEntityQueue);
                Collections.sort(streamEntityQueue);
                LogUtils.e(Utils.TAG, "OutSiteStreamInfoParser after sort streamEntityQueue is " + streamEntityQueue);
                streamInfo.setStreamEntityQueue(streamEntityQueue);
                streamInfo.setAllFormatsList(formatsList);
                streamInfo.setIsRetry(false);
            } else {
                LogUtils.e(Utils.TAG, "OutSiteStreamInfoParser newversion data is null");
                streamInfo.setIsRetry(true);
            }
        }
        return streamInfo;
    }

    /**
     * 解析
     *
     * @param array
     * @return
     */
    private List<String> setListValue(JSONArray array) {
        List<String> strList = new ArrayList();
        if (array != null)
            for (int i = 0; i < array.length(); i++) {
                if (!TextUtils.isEmpty(array.optString(i))) {
                    strList.add(array.optString(i));
                }
            }
        return strList;
    }

    /**
     * 根据 type 设置播放或者下载优先级
     *
     * @param osType
     * @param requestFormat
     * @param type
     * @return
     */
    private int getStreamPriority(String osType, String requestFormat, int type) {
        int priority = -1;
        if (type == Utils.STREAM_PLAY) {
            LogUtils.e(Utils.TAG, "!!!!!!!!!!!!!play set priority");
            if (ANDROID.equalsIgnoreCase(osType)) {
                if (NORMAL.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.ANDROID_NORMAL.ordinal();
                if (HIGH.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.ANDROID_HIGH.ordinal();
                if (SUPER.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.ANDROID_SUPER.ordinal();
                if (SUPER2.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.ANDROID_SUPER2.ordinal();
                if (REAL.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.ANDROID_REAL.ordinal();
            }
            if (IOS.equalsIgnoreCase(osType)) {
                if (NORMAL.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.IOS_NORMAL.ordinal();
                if (HIGH.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.IOS_HIGH.ordinal();
                if (SUPER.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.IOS_SUPER.ordinal();
                if (SUPER2.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.IOS_SUPER2.ordinal();
                if (REAL.equalsIgnoreCase(requestFormat))
                    priority = StreamPlayPriority.IOS_REAL.ordinal();
            }
        }
        if (type == Utils.STREAM_DOWN) {
            LogUtils.e(Utils.DOWN_TAG, "!!!!!!!!!!!!!down set priority");
            if (ANDROID.equalsIgnoreCase(osType)) {
                if (NORMAL.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.ANDROID_NORMAL.ordinal();
                if (HIGH.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.ANDROID_HIGH.ordinal();
                if (SUPER.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.ANDROID_SUPER.ordinal();
                if (SUPER2.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.ANDROID_SUPER2.ordinal();
                if (REAL.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.ANDROID_REAL.ordinal();
            }
            if (IOS.equalsIgnoreCase(osType)) {
                if (NORMAL.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.IOS_NORMAL.ordinal();
                if (HIGH.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.IOS_HIGH.ordinal();
                if (SUPER.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.IOS_SUPER.ordinal();
                if (SUPER2.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.IOS_SUPER2.ordinal();
                if (REAL.equalsIgnoreCase(requestFormat))
                    priority = StreamDownNewPriority.IOS_REAL.ordinal();
            }
        }
        return priority;
    }
}
